from todo import Todo
from utils import redirect, template, http_response


def index(request):
    # 主页处理函数,返回主页的响应
    todo_list = Todo.all()
    body = template('todo_index.html', todos=todo_list)
    return http_response(body)


# def login_required(route_function):
#     def f(request):
#         uname = current_user(request)
#         u = User.find_by(username=uname)
#         if u is None:
#             return redirect('/login')
#         return route_function(request)
#
#     return f


def add(request):
    # headers = {
    #     'Content-Type': 'text/html',
    # }
    # uname = current_user(request)
    # u = User.find_by(username=uname)
    # if request.method == 'POST':
    form = request.form()
    # t = Todo.new(form)
    Todo.new(form)
    #     t.user_id = u.id
    #     t.save()
    # return redirect('/todo')
    return redirect('/todo')


def delete(request):
    # uname = current_user(request)
    # u = User.find_by(username=uname)
    # if u is None:
    #     return redirect('/login')
    # todo_id = int(request.query.get('id', -1))
    todo_id = int(request.query.get('id'))
    # t = Todo.find_by(id=todo_id)
    # if t.user_id != u.id:
    #     return redirect('/login')
    # if t is not None:
    #     t.remove()
    Todo.delete(todo_id)
    return redirect('/todo')


def edit(request):
    # headers = {
    #     'Content-Type': 'text/html',
    # }
    # uname = current_user(request)
    # u = User.find_by(username=uname)
    # if u is None:
    #     return redirect('/login')
    todo_id = int(request.query.get('id', -1))
    t = Todo.find_by(id=todo_id)
    # if t.user_id != u.id:
    #     return redirect('/login')
    # body = template('todo_edit.html')
    # body = body.replace('{{todo_id}}', str(t.id))
    # body = body.replace('{{todo_title}}', str(t.title))
    body = template('todo_edit.html', todo=t)
    # header = response_with_headers(headers)
    # r = header + '\r\n' + body
    # return r.encode(encoding='utf-8')
    return http_response(body)


def update(request):
    todo_id = int(request.query.get('id'))
    # uname = current_user(request)
    # u = User.find_by(username=uname)
    # if u is None:
    #     return redirect('/login')
    # if request.method == 'POST':
    form = request.form()
    #     todo_id = int(form.get('id', -1))
    t = Todo.find_by(id=todo_id)
    #     t.title = form.get('title', t.title)
    t.task = form.get('task')
    t.save()
    return redirect('/todo')


route_dict = {
    # GET 请求,显示页面
    # '/todo': index,
    '/todo': index,
    '/todo/edit': edit,
    # POST请求，处理数据
    # '/todo/add': add,
    '/todo/add': add,
    '/todo/delete': delete,
    '/todo/update': update,
}
